package cn.itcast.bos.service.system.impl;

import java.util.List;
import java.util.Map;

import cn.itcast.bos.mapper.MenuMapper;
import cn.itcast.bos.pagehelper.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.MenuService;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {


	@Autowired
	private MenuMapper menuMapper;

	@Override
	public List<Menu> menuList(User user) {
		if(user != null && "admin".equals(user.getUsername()) ){
			return menuMapper.menuList();
		}
		System.out.println(menuMapper.menuListByUsername(user));
		return menuMapper.menuListByUsername(user);
	}

    @Override
    public List<Menu> menuList() {
        return menuMapper.menuList();
    }


    @Override
	public PageResult findPageMenu(int pageNum, int pageSize,Menu menu) {
		PageHelper.startPage(pageNum,pageSize);
		Page<Menu> pages = (Page<Menu>) menuMapper.findPageMenu(menu);
		return new PageResult(pages.getTotal(),pages.getResult());
	}

	@Override
	public Menu selectMenuById(int id) {
		return menuMapper.selectMenuById(id);
	}

	@Override
	public List<Map<String, Object>> parentMenuList() {
		return menuMapper.parentMenuList();
	}

	@Override
	public void insert(Menu menu) {
		menuMapper.insert(menu);
	}

	@Override
	public void update(Menu menu) {
		menuMapper.update(menu);
	}

	@Override
	public void delete(String[] ids) {
		for (String id : ids) {
			delById(Integer.parseInt(id));
		}
	}

	//递归查询删除:
	public void delById(Integer id){
		Menu menu = menuMapper.findMenuByParentId(id);
		if(menu != null && menu.getpId() != null){
			delById(menu.getId());
			//把子节点删掉后把父节点干掉
			menuMapper.delete(menu.getpId());
		}else{
			//没有子菜单直接删除:
			menuMapper.delete(id);
		}
	}

}